from fastapi import APIRouter, Depends, HTTPException, Request, Form, status
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from pathlib import Path
from app.database import User, get_db, get_password_hash

router = APIRouter(tags=["认证"])

# 设置模板目录
templates = Jinja2Templates(directory=str(Path(__file__).parent.parent / "templates"))

@router.get("/login", response_class=HTMLResponse)
async def show_login_page(request: Request):
    """显示登录页面"""
    return templates.TemplateResponse("login.html", {"request": request})

@router.post("/login")
async def handle_login(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    db: Session = Depends(get_db)
):
    """处理登录表单提交"""
    user = db.query(User).filter(User.username == username).first()
    
    if not user:
        return templates.TemplateResponse(
            "login.html",
            {"request": request, "error": "用户名或密码错误"},
            status_code=status.HTTP_401_UNAUTHORIZED
        )
    
    if not user.verify_password(password):
        return templates.TemplateResponse(
            "login.html",
            {"request": request, "error": "用户名或密码错误"},
            status_code=status.HTTP_401_UNAUTHORIZED
        )
    
    # 在实际应用中，这里应该创建并返回一个认证token
    return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)

@router.get("/register", response_class=HTMLResponse)
async def show_register_page(request: Request):
    """显示注册页面"""
    return templates.TemplateResponse("register.html", {"request": request})

@router.post("/register", response_class=HTMLResponse)
async def handle_register(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    db: Session = Depends(get_db)
):
    """处理注册表单提交"""
    # 检查用户名是否已存在
    existing_user = db.query(User).filter(User.username == username).first()
    if existing_user:
        return templates.TemplateResponse(
            "register.html",
            {"request": request, "error": "用户名已存在"},
            status_code=status.HTTP_400_BAD_REQUEST
        )
    
    # 创建新用户
    hashed_password = get_password_hash(password)
    new_user = User(username=username, hashed_password=hashed_password)
    db.add(new_user)
    db.commit()
    
    # 注册成功后重定向到登录页面
    return RedirectResponse(url="/api/login", status_code=status.HTTP_303_SEE_OTHER)